package com.ffs.game.scene.obj.ai.fsm;

import com.ffs.game.scene.GameScene;
import com.ffs.game.scene.obj.Monster;
import com.ffs.game.scene.obj.ai.AIData;
import com.ffs.game.scene.obj.ai.MonsterState;
import com.ffs.persist.utils.TimeUtil;

import java.util.Map;

/**
 * 状态机
 *
 * @author ffs80
 */
public class FSMMachine<T extends AbstractFSMState<MonsterState, Monster>> {

    /**
     * 所有可用状态
     */
    private final Map<MonsterState, T> states;

    /**
     * 当前状态
     */
    private T curState;

    /**
     * AI数据
     */
    private final AIData aiData = new AIData();

    /**
     * 构造
     *
     * @param states    可用状态集合
     * @param initState 初始状态
     */
    public FSMMachine(Map<MonsterState, T> states, T initState) {
        this.states = states;
        this.curState = initState;
        aiData.setBornTime(TimeUtil.getNowMils());
    }

    /**
     * 状态机更新
     */
    public void update(GameScene screen, int delta) {
        if (states.isEmpty()) {
            return;
        }

        if (curState == null) {
            return;
        }

        MonsterState nextEnumState = curState.checkTransfer(screen);
        MonsterState curEnumState = this.curState.findState();
        if (nextEnumState != curEnumState) {
            T nextSate = findState(nextEnumState);
            if (nextSate != null) {
                //当前状态执行退出操作
                curState.exit(screen);
                //切换状态
                curState = nextSate;
                //进入下一状态
                curState.enter(screen);
                return;
            }
        }

        curState.update(screen, delta);
    }

    /**
     * 获取AI数据
     */
    public AIData getAiData() {
        return aiData;
    }

    private T findState(MonsterState monsterState) {
        return states.get(monsterState);
    }
}
